﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace Omu.Awesome.Mvc.Helpers
{
    public static class AjaxDropdownHelpers
    {
        public static MvcHtmlString AjaxDropdownFor<T, TReturn>(
            this HtmlHelper<T> html,
            Expression<Func<T, TReturn>> prop,
            object value = null,
            string controller = null,
            string parentId = null,
            object htmlAttributes = null,
            string prefix = null,
            IDictionary<string, string> data = null)
        {
            return AjaxDropdown(html, ExpressionHelper.GetExpressionText(prop), value, controller, parentId, htmlAttributes, prefix, data);
        }

        public static MvcHtmlString AjaxDropdown(
            this HtmlHelper html,
            string prop,
            object value = null,
            string controller = null,
            string parentId = null,
            object htmlAttributes = null,
            string prefix = null,
            IDictionary<string, string> data = null)
        {
            if (html.ViewData.ModelMetadata != null)
            {
                var vals = html.ViewData.ModelMetadata.AdditionalValues;
                controller = (string)controller.FromMeta("controller", vals);
                parentId = (string)parentId.FromMeta("parentId", vals);
            }

            if (controller == null) controller = prop.GetController() + "AjaxDropdown";
            value = value.FromModel(html, prop);
            var hd = htmlAttributes.GetDictionary();
            var h = !html.ViewData.ModelState.IsValidField(prop)
                        ? hd.AddVal("class", "input-validation-error")
                        : hd;
            return html.Partial(Settings.AwesomeFolder + "AjaxDropdown.ascx",
                new AjaxDropdownInfo
                {
                    Prop = prop,
                    Value = value,
                    Controller = controller,
                    ParentId = parentId,
                    HtmlAttributes = h.ToHtml(),
                    Prefix = prefix,
                    Data = data
                });
        }

    }
}